// pages/nowOrder/nowOrder.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        nowIdx: 0,
        repairmanList: [
            '所有', '水工', '电工', '泥工', '木工',
        ],
        orderList: [],
        tempList: []
    },

    getOrderList: async (that) => {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        const res = (await wx.cloud.callFunction({ name: 'getOrderList' })).result;
        await that.setData({ orderList: res });
        await that.changeOrderType();
    },

    acceptOrder(e) {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        const idx = e.target.dataset.idx;
        const repairmanID = getApp().globalData.user.sid;
        const orderID = this.data.orderList[idx]._id;
        wx.cloud.callFunction({
            name: 'acceptOrder',
            data: {
                repairmanID: repairmanID,
                orderID: orderID,
            }
        }).then(res => {
            if (res.result !== true) throw "accept unsuccessfully"
            this.getOrderList(this).then(res => wx.showToast({
                title: '接受成功',
                icon: 'success',
            })).catch(err => wx.showToast({
                title: '出错了',
                icon: 'error'
            }));
        }).catch(err => wx.showToast({
            title: '出错了',
            icon: 'error'
        }));
    },

    changeOrderType(e) {
        var idx = 0;
        if (e) idx = e.target.dataset.idx;
        this.setData({ nowIdx: idx });
        if (idx) this.setData({
            tempList: this.data.orderList.filter(item => {
                return item.project === this.data.repairmanList[idx];
            })
        }); else this.setData({ tempList: this.data.orderList });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        wx.showLoading({
            title: '加载中',
            mask: true
        });
        this.getOrderList(this).then(res => {
            wx.hideLoading();
        }).catch(err => wx.showToast({
            title: '出错了',
            icon: 'error'
        }));
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})